<?php
/*
  开发作者：南阳迈特网络科技有限公司
  QQ:794929988
*/

namespace addons\drama\controller;

use addons\drama\library\Wechat as WechatLibrary;
use addons\drama\model\Config;
use addons\drama\model\Wechat as WechatModel;
use EasyWeChat\Kernel\Exceptions\HttpException;
use think\Cache;
use addons\drama\model\ResellerOrder;
use addons\drama\model\UsableOrder;
use addons\drama\model\VipOrder;
use think\Log;
use think\Db;
use addons\drama\model\ResellerBind;
use addons\drama\model\ResellerLog;
use addons\drama\model\VideoOrder as VideoOrderModel;
use app\admin\model\drama\Recharge as RechargeModel;
use think\Collection;

/**
 * 微信接口
 * @ApiInternal
 */
class Wechat extends Base
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $app = null;
    protected $userOpenId = '';
    // 用户充值滚动播报6-10条（昵称、时间、充值金额）
    public function recharge_user_list()
    {
        $w = [];
        $w['site_id'] = $this->site_id;
        $w['status'] = 1;
        $w1 = [];
        $w1['v.site_id'] = $this->site_id;
        $w1['v.status'] = ['in', [1, 2]];
        // dump($w1);
        // 用户充值管理 user_id
        $recharge_list1 = Collection::make(\addons\drama\model\VipOrder::alias('v')
            ->join('user u', 'u.id= v.user_id')
            ->where($w1)
            ->limit(3)->field('v.id,v.site_id,u.nickname as name,v.total_fee as price,paytime as time,v.status,v.user_id')->order('v.id', 'desc')->select())->toArray();
        $recharge_list2 = Collection::make(\app\admin\model\drama\ResellerOrder::alias('v')
            ->join('user u', 'u.id= v.user_id')
            ->where($w1)
            ->limit(3)->field('v.id,v.site_id,u.nickname as name,v.total_fee as price,paytime as time,v.status,v.user_id')->order('v.id', 'desc')->select())->toArray();
        $recharge_list3 = Collection::make(\app\admin\model\drama\UsableOrder::alias('v')
            ->join('user u', 'u.id= v.user_id')
            ->where($w1)
            ->limit(3)->field('v.id,v.site_id,u.nickname as name,v.total_fee as price,paytime as time,v.status,v.user_id')->order('v.id', 'desc')->select())->toArray();
        // dump($recharge_list3);
        $co = 8 - count($recharge_list1) - count($recharge_list2) - count($recharge_list3);
        $recharge_list = Collection::make(RechargeModel::where($w)->limit($co)->field('id,site_id,title as name,price,time,status')->order('id', 'desc')->select())->toArray();
        foreach ($recharge_list as $k => $v) {
            $time = strtotime(date('Y-m-d'));
            if ($v['time'] < $time) {
                $up_time = strtotime(date('Y-m-d') . ' ' . rand(1, 24) . ':' . rand(1, 60) . ':' . rand(1, 60));
                RechargeModel::where(['id' => $v['id']])->update(['time' => $up_time]);
                $recharge_list[$k]['time'] = $up_time;
            }
        }
        $recharge_list = array_merge($recharge_list, $recharge_list1);
        $recharge_list = array_merge($recharge_list, $recharge_list2);
        $recharge_list = array_merge($recharge_list, $recharge_list3);
        foreach ($recharge_list as $k => &$v) {
            $v['time'] = date('Y-m-d H:i:s', $v['time']);
            // $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
            // $v['updatetime'] = date('Y-m-d H:i:s', $v['updatetime']);
        }
        $data['recharge_list'] = $recharge_list;
        // 期权制
        $Optionmodel = new \app\admin\model\drama\Option;
        $option_sum = array_sum(array_column(Collection::make($Optionmodel->where(['site_id' => $this->site_id, 'status' => '1'])->order('id', 'desc')->select())->toArray(), 'option')); //系统的期权值
        $option_sum2 = array_sum(array_column(Collection::make($Optionmodel->where(['site_id' => $this->site_id, 'status' => '0'])->order('id', 'desc')->select())->toArray(), 'option')); //已经送出的期权值
        $data['option_sum'] = bcsub($option_sum, $option_sum2, 2);
        // 人气演员榜单
        $data['membersnumber_list'] = Collection::make(\app\admin\model\drama\Membersnumber::where($w)->field('id,site_id,performer_id,count,status')->limit(6)->order(['count' => 'desc', 'weigh' => 'asc'])->select())->toArray();
        foreach ($data['membersnumber_list'] as $k => &$v) {
            $i = \app\admin\model\drama\Membersnumber::where($w)->field('id,site_id,performer_id,count,status')->order(['count' => 'desc', 'weigh' => 'asc'])->limit(1)->find();
            $total = $i->count; //总数
            $num   = $v['count']; //数量
            $bfb = round($num / $total * 100, 2) . "%"; //数量再除总数，得出百分比
            $v['bfb'] = $bfb;
        }
        // 推剧达人月数据
        $reseller_list = \app\admin\model\drama\Reseller::where(['status' => 'normal', 'site_id' => $this->site_id])->field('id,site_id,name')->select();
        foreach ($reseller_list as $k => &$v) {
            $v['count'] = \app\admin\model\drama\Resellerlist::where($w)->where(['reseller_id' => $v['id']])->sum('count');
        }
        $data['resellerlist_list'] = Collection::make($reseller_list)->toArray();
        // 充值汇总
        $arr = ['w', 'm', 'q'];
        $rechargelist_list = [];
        $Rechargelist = new \app\admin\model\drama\Rechargelist;
        foreach ($arr as $k => $v) {
            $rechargelist_list[$k]['price'] = $Rechargelist->where($w)->where(['type' => $v])->sum('price');
            $type_text = $Rechargelist->getTypeList();
            $rechargelist_list[$k]['type_text'] = $type_text[$v];
        }
        $data['rechargelist_list'] = $rechargelist_list;
        // 会员汇总
        $arr = ['w', 'm'];
        $user_list = [];
        $Userlist = new \app\admin\model\drama\Userlist;
        // 查询本周新增的会员数
        foreach ($arr as $k => $v) {
            if ($v == 'w') {
                // $week = Db::name('user')->where(['status' => 'normal', 'site_id' => $this->site_id])->whereTime('createtime', 'week')->count();
                $user_list[$k]['price'] = $Userlist->where($w)->where(['type' => $v])->sum('count');
            } else {
                // $month = Db::name('user')->where(['status' => 'normal', 'site_id' => $this->site_id])->whereTime('createtime', 'month')->count();
                $user_list[$k]['price'] = $Userlist->where($w)->where(['type' => $v])->sum('count');
            }
            $type_text = $Userlist->getTypeList();
            $user_list[$k]['type_text'] = $type_text[$v];
        }
        $data['user_list'] = $user_list;
        // 短剧人气榜单
        $Videomodel = new \addons\drama\model\Video;
        $vw = [];
        $vw['v.status'] = 'up';
        $vw['dve.status'] = 'normal';
        $video_list = $Videomodel->alias('v')
            ->join('drama_video_episodes dve', 'dve.vid=v.id')
            ->field('v.id,v.title,v.image,sum(dve.views)+sum(dve.fake_views) as dve_views')
            ->where($vw)
            ->group('v.id')
            ->order(['dve_views' => 'desc'])
            ->limit('6')
            ->select();
        $data['video_list'] = Collection::make($video_list)->toArray();
        // dump($data);
        return json($data);
    }
    public function recharge_user_list1()
    {
        $w = [];
        $w['site_id'] = $this->site_id;
        $w['status'] = 1;
        $w1 = [];
        $w1['v.site_id'] = $this->site_id;
        $w1['v.status'] = ['in', [1, 2]];
        // dump($w1);
        // 用户充值管理 user_id
        $recharge_list1 = Collection::make(\addons\drama\model\VipOrder::alias('v')
            ->join('user u', 'u.id= v.user_id')
            ->where($w1)
            ->limit(3)->field('v.id,v.site_id,u.nickname as name,v.total_fee as price,paytime as time,v.status,v.user_id')->order('v.id', 'desc')->select())->toArray();
        $recharge_list2 = Collection::make(\app\admin\model\drama\ResellerOrder::alias('v')
            ->join('user u', 'u.id= v.user_id')
            ->where($w1)
            ->limit(3)->field('v.id,v.site_id,u.nickname as name,v.total_fee as price,paytime as time,v.status,v.user_id')->order('v.id', 'desc')->select())->toArray();
        $recharge_list3 = Collection::make(\app\admin\model\drama\UsableOrder::alias('v')
            ->join('user u', 'u.id= v.user_id')
            ->where($w1)
            ->limit(3)->field('v.id,v.site_id,u.nickname as name,v.total_fee as price,paytime as time,v.status,v.user_id')->order('v.id', 'desc')->select())->toArray();
        // dump($recharge_list3);
        $co = 8 - count($recharge_list1) - count($recharge_list2) - count($recharge_list3);
        $recharge_list = [];
        $recharge_list = Collection::make(RechargeModel::where($w)->field('id,site_id,title as name,price,time,status')->order('id', 'desc')->select())->toArray();
        foreach ($recharge_list as $k => $v) {
            $time = strtotime(date('Y-m-d'));
            if ($v['time'] < $time) {
                $up_time = strtotime(date('Y-m-d') . ' ' . rand(1, 24) . ':' . rand(1, 60) . ':' . rand(1, 60));
                RechargeModel::where(['id' => $v['id']])->update(['time' => $up_time]);
                $recharge_list[$k]['time'] = $up_time;
            }
        }
        $recharge_list = array_merge($recharge_list, $recharge_list1);
        $recharge_list = array_merge($recharge_list, $recharge_list2);
        $recharge_list = array_merge($recharge_list, $recharge_list3);
        foreach ($recharge_list as $k => &$v) {
            $v['time'] = date('Y-m-d H:i:s', $v['time']);
            // $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
            // $v['updatetime'] = date('Y-m-d H:i:s', $v['updatetime']);
        }
        // dump($recharge_list);
        $data['recharge_list'] = $recharge_list;
        // 期权制
        $Optionmodel = new \app\admin\model\drama\Option;
        $option_sum = array_sum(array_column(Collection::make($Optionmodel->where(['site_id' => $this->site_id, 'status' => '1'])->order('id', 'desc')->select())->toArray(), 'option')); //系统的期权值
        $option_sum2 = array_sum(array_column(Collection::make($Optionmodel->where(['site_id' => $this->site_id, 'status' => '0'])->order('id', 'desc')->select())->toArray(), 'option')); //已经送出的期权值
        $data['option_sum'] = bcsub($option_sum, $option_sum2, 2);
        // 人气演员榜单
        $data['membersnumber_list'] = Collection::make(\app\admin\model\drama\Membersnumber::where($w)->field('id,site_id,performer_id,count,status')->limit(6)->order(['count' => 'desc', 'weigh' => 'asc'])->select())->toArray();
        foreach ($data['membersnumber_list'] as $k => &$v) {
            $i = \app\admin\model\drama\Membersnumber::where($w)->field('id,site_id,performer_id,count,status')->order(['count' => 'desc', 'weigh' => 'asc'])->limit(1)->find();
            $total = $i->count; //总数
            $num   = $v['count']; //数量
            $bfb = round($num / $total * 100, 2) . "%"; //数量再除总数，得出百分比
            $v['bfb'] = $bfb;
        }
        dump($data['membersnumber_list']);

        // $total = $i->count;//总数
        // $num   = 50;//数量
        // $bfb = round($num / $total * 100,2)."%";//数量再除总数，得出百分比
        // echo $bfb;//输出内容
        // 推剧达人月数据
        $reseller_list = \app\admin\model\drama\Reseller::where(['status' => 'normal', 'site_id' => $this->site_id])->field('id,site_id,name')->select();
        foreach ($reseller_list as $k => &$v) {
            $v['count'] = \app\admin\model\drama\Resellerlist::where($w)->where(['reseller_id' => $v['id']])->sum('count');
        }
        $data['resellerlist_list'] = Collection::make($reseller_list)->toArray();
        // 充值汇总
        $arr = ['w', 'm', 'q'];
        $rechargelist_list = [];
        $Rechargelist = new \app\admin\model\drama\Rechargelist;
        foreach ($arr as $k => $v) {
            $rechargelist_list[$k]['price'] = $Rechargelist->where($w)->where(['type' => $v])->sum('price');
            $type_text = $Rechargelist->getTypeList();
            $rechargelist_list[$k]['type_text'] = $type_text[$v];
        }
        $data['rechargelist_list'] = $rechargelist_list;
        // 会员汇总
        $arr = ['w', 'm'];
        $user_list = [];
        $Userlist = new \app\admin\model\drama\Userlist;
        // 查询本周新增的会员数
        foreach ($arr as $k => $v) {
            if ($v == 'w') {
                $week = Db::name('user')->where(['status' => 'normal', 'site_id' => $this->site_id])->whereTime('createtime', 'week')->count();
                $user_list[$k]['price'] = $Userlist->where($w)->where(['type' => $v])->sum('count') + $week;
            } else {
                $month = Db::name('user')->where(['status' => 'normal', 'site_id' => $this->site_id])->whereTime('createtime', 'month')->count();
                $user_list[$k]['price'] = $Userlist->where($w)->where(['type' => $v])->sum('count') + $month;
            }
            $type_text = $Userlist->getTypeList();
            $user_list[$k]['type_text'] = $type_text[$v];
        }
        $data['user_list'] = $user_list;
        // 短剧人气榜单
        $Videomodel = new \addons\drama\model\Video;
        $vw = [];
        $vw['v.status'] = 'up';
        $vw['dve.status'] = 'normal';
        $video_list = $Videomodel->alias('v')
            ->join('drama_video_episodes dve', 'dve.vid=v.id')
            ->field('v.id,v.title,v.image,sum(dve.views)+sum(dve.fake_views) as dve_views')
            ->where($vw)
            ->group('v.id')
            ->order(['dve_views' => 'desc'])
            ->select();
        $data['video_list'] = Collection::make($video_list)->toArray();
        dump($data);
        // return json($data);
    }
    /**
     * 微信公众号服务端API对接、处理消息回复
     */
    public function index()
    {
        if (isset($_GET['echostr'])) {
            $this->valid();
        }
        $sign = request()->param('sign');
        $wechat = new WechatLibrary('wxOfficialAccount', $sign);
        $this->app = $wechat->getApp();
        $this->app->server->push(function ($message) {
            //初始化信息
            $this->userOpenId = $message['FromUserName'];
            // return json_encode($message, JSON_UNESCAPED_UNICODE); //调试使用

            switch ($message['MsgType']) {
                case 'event': //收到事件消息
                    switch ($message['Event']) {
                        case 'subscribe': //订阅（关注）事件
                            // 关注回复 使用客服接口回复
                            $subscribe = WechatModel::get(['type' => 'subscribe', 'site_id' => $this->site_id]);
                            if ($subscribe) {
                                $sub_content = json_decode($subscribe['content'], true);
                                switch ($sub_content['type']) {
                                    case 'text':  //回复文本
                                        $sub_content = new \EasyWeChat\Kernel\Messages\Text($sub_content['content']);
                                        $this->app->customer_service->message($sub_content)->to($this->userOpenId)->send();
                                        break;
                                    case 'image': //回复图片
                                        $sub_content = new \EasyWeChat\Kernel\Messages\Image($sub_content['media_id']);
                                        $this->app->customer_service->message($sub_content)->to($this->userOpenId)->send();
                                        break;
                                    case 'news': //回复图文
                                        $sub_content = new \EasyWeChat\Kernel\Messages\Media($sub_content['media_id'], 'mpnews');
                                        $this->app->customer_service->message($sub_content)->to($this->userOpenId)->send();
                                        break;
                                    case 'voice': //回复语音
                                        $sub_content = new \EasyWeChat\Kernel\Messages\Voice($sub_content['media_id']);
                                        $this->app->customer_service->message($sub_content)->to($this->userOpenId)->send();
                                        break;
                                    case 'video': //回复视频
                                        $sub_content = new \EasyWeChat\Kernel\Messages\Video($sub_content['media_id']);
                                        $this->app->customer_service->message($sub_content)->to($this->userOpenId)->send();
                                        break;
                                    case 'link': //回复链接
                                        $items = new  \EasyWeChat\Kernel\Messages\NewsItem([
                                            'title'       => $sub_content['title'],
                                            'description' => $sub_content['description'],
                                            'url'         => $sub_content['url'],
                                            'image'       => cdnurl($sub_content['image'], true),
                                        ]);
                                        $sub_content = new \EasyWeChat\Kernel\Messages\News([$items]);
                                        $this->app->customer_service->message($sub_content)->to($this->userOpenId)->send();
                                }
                            }
                            // 授权登录需要发送授权事件
                            if ($message['EventKey'] == null) {
                                return '';
                            }
                            return $this->response($message, 'subscribe');
                            break;
                        case 'unsubscribe': //取消订阅（关注）事件
                            break;
                        case 'CLICK':  //自定义菜单事件
                            return $this->response($message, 'CLICK');
                            break;
                        case 'SCAN': //扫码事件
                            return $this->response($message, 'SCAN');
                            break;
                        case 'xpay_goods_deliver_notify':

                            Log::write('notifyx-result:' . json_encode($message), 'xunipay');

                            try {
                                $out_trade_no = $message['OutTradeNo'];

                                if (strpos($out_trade_no, 'TO') === 0) {
                                    // VIP订单
                                    $prepay_type = 'vip';
                                    $order = new VipOrder();
                                } else if (strpos($out_trade_no, 'AO') === 0) {
                                    // 剧场积分充值订单
                                    $prepay_type = 'usable';
                                    $order = new UsableOrder();
                                } else {
                                    // 分销商订单
                                    $prepay_type = 'reseller';
                                    $order = new ResellerOrder();
                                }

                                $order = $order->where('order_sn', $out_trade_no)->find();

                                //Log::write('notifyx-result:'. json_encode($order),'xunipay');

                                if (!$order || $order->status > 0) {
                                    // 订单不存在，或者订单已支付
                                    echo json_encode(['ErrCode' => 0]);
                                    exit;
                                }

                                $notify = [
                                    'order_sn' => $message['OutTradeNo'],
                                    'transaction_id' => $message['WeChatPayInfo']['TransactionId'],
                                    'notify_time' => date('Y-m-d H:i:s', $message['CreateTime']),
                                    'buyer_email' => $message['OpenId'],
                                    'payment_json' => json_encode($message),
                                    'pay_fee' => bcdiv($message['GoodsInfo']['ActualPrice'], 100, 2),
                                    'pay_type' => 'wechat'              // 支付方式
                                ];
                                $order->paymentProcess($order, $notify);
                                echo json_encode(['ErrCode' => 0]);
                            } catch (\Exception $e) {
                                Log::write('notifyx-error:' . json_encode($e->getMessage()), 'xunipay');
                            }

                            exit;

                            break;
                    }
                    break;
                case 'text': //收到文本消息
                    //检测关键字回复
                    $content = $message['Content'];
                    $auto_reply = WechatModel::where('site_id', $this->site_id)
                        ->where('type', 'auto_reply')
                        ->where('find_in_set(:keywords,rules)', ['keywords' => $content])
                        ->find();
                    if ($auto_reply) {
                        return $this->response($auto_reply);
                    }
                case 'image': //收到图片消息
                case 'voice': //收到语音消息
                case 'video': //收到视频消息
                case 'location': //收到坐标消息
                case 'link': //收到链接消息
                case 'file': //收到文件消息
                default: // ... 默认回复消息
                    $default_reply = WechatModel::where('site_id', $this->site_id)->where('type', 'default_reply')->find();
                    if ($default_reply) {
                        return $this->response($default_reply);
                    }
            }
        });
        $response = $this->app->server->serve();
        // 将响应输出
        $response->send();
    }

    /**
     * 微信小程序码
     */
    public function wxacode()
    {
        $scene = $this->request->get('scene', '');
        $path = $this->request->get('path', '');

        if (empty($path)) {
            $path = 'pages/home/index';
        }

        try {
            $wechat = new WechatLibrary('wxMiniProgram');
            $content = $wechat->getApp()->app_code->getUnlimit($scene, [
                'page' => $path,
                'is_hyaline' => true,
            ]);
        } catch (HttpException $e) {
            $this->error('小程序配置信息错误:' . $e->getMessage());
        }

        if ($content instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            return response($content->getBody(), 200, ['Content-Length' => strlen($content)])->contentType('image/png');
        } else {
            // 小程序码获取失败
            $msg = isset($content['errcode']) ? $content['errcode'] : '-';
            $msg .= isset($content['errmsg']) ? $content['errmsg'] : '';
            \think\Log::write('wxacode-error' . $msg);

            $this->error('获取失败', $msg);
        }
    }
    public function user_grade($user_id, $arr = [], $lv = [], $reseller_user_arr = [])
    {
        // 查询所有的比自身等级大的数据
        $reseller_user = Db::name('drama_reseller_user')
            ->where('user_id', $user_id)
            ->where('type', 1)
            ->find();
        if ($reseller_user) {
            $reseller_bind = ResellerBind::where('user_id', $reseller_user['reseller_user_id'])->find()->toArray();
            $user_info = Db::name('user')->find($reseller_user['reseller_user_id']);
            if ($reseller_bind && $user_info) {
                if ($reseller_bind['level'] <= 3) {
                    if ($lv[count($lv) - 1] <= $reseller_bind['level'] || count($lv) == 0) {
                        if (!in_array($reseller_bind['level'], $lv)) {
                            $lv[] = $reseller_bind['level'];
                            $arr[$reseller_bind['level']] = $reseller_user['reseller_user_id'];
                            $reseller_user_arr[$reseller_bind['level']] = $reseller_user;
                        }
                    }
                    return $this->user_grade($reseller_user['reseller_user_id'], $arr, $lv, $reseller_user_arr);
                }
            }
        }
        return [$arr, $reseller_user_arr];
    }
    /**
     * 根据订单号获取订单实例
     * @ApiInternal
     * @param [type] $order_sn
     * @return void
     */
    private function getOrderInstance($order_sn)
    {
        if (strpos($order_sn, 'TO') === 0) {
            // VIP订单
            $prepay_type = 'vip';
            $order = new VipOrder();
        } else if (strpos($order_sn, 'AO') === 0) {
            // 剧场积分充值订单
            $prepay_type = 'usable';
            $order = new UsableOrder();
        } else {
            // 分销商订单
            $prepay_type = 'reseller';
            $order = new ResellerOrder();
        }

        return [$order, $prepay_type];
    }
    private function payResponse($pay = null, $payment = null)
    {
        // return $pay->success()->send();
    }
    public function fanyong()
    {
        $order = new ResellerOrder();
        $order = $order->find(179);
        // dump($order);
        $order_type = 'vip';

        if (in_array($order['status'], [1, 2])) {
            $reseller_user = Db::name('drama_reseller_user')
                ->where('user_id', $order['user_id'])
                ->where('type', 1)
                ->find();
            // dump($reseller_user);

            $option = 0;
            if ($order_type == 'reseller') {
                $option = Db::name('drama_reseller')->where(['id' => $order['reseller_id']])->value('option');
                // Db::name('user')->where('id', $order['user_id'])->setInc('option', $option);
                if ($option > 0) {
                    $Optionmodel = new \app\admin\model\drama\Option;
                    $option_save = [];
                    $option_save['site_id'] = $order['site_id'];
                    $option_save['title'] = '后台赠送';
                    $option_save['option'] = $option;
                    $option_save['status'] = 0;
                    $option_save['weigh'] = 0;
                    $option_save['uid'] = $order['user_id'];
                    // dump($option_save);
                    // $Optionmodel->save($option_save);
                }
            }
            list($arr, $reseller_user_arr) = $this->user_grade($reseller_user['user_id']);
            $level = 1;
            $option1 = array_sum(Db::name('drama_option')->where(['site_id' => $order['site_id'], 'status' => '1'])->column('option'));
            $option0 = array_sum(Db::name('drama_option')->where(['site_id' => $order['site_id'], 'status' => '0'])->column('option'));
            $a = bcsub($option1, $option0, 2);
            // 只有直推有期权制
            if ($order_type == 'reseller') {
                if ($option == $option0) {
                    $option = 0;
                } else if ($a < 0) {
                    $option = 0;
                } else if (bcsub($a, $option, 2) < 0) {
                    $option = $a;
                }
            } else {
                $option = 0;
            }
            $d_r_sum = array_sum(Db::name('drama_reseller')->where(['status' => 'normal', 'level' => ['in', '2,3']])->column('range'));
            $key_arr=array_flip($arr);
            foreach ($arr as $k => $v) {

                $reseller_bind = ResellerBind::where('user_id', $v)->find()->toArray();
                $drama_reseller = Db::name('drama_reseller')->find($reseller_bind['reseller_id']);
                if ($order_type == 'usable') {
                    $drama_reseller['direct'] = $drama_reseller['direct_pf'];
                    $drama_reseller['range'] = $drama_reseller['range_pf'];
                    $drama_reseller['indirect'] = $drama_reseller['indirect_pf'];
                    $d_r_sum = array_sum(Db::name('drama_reseller')->where(['status' => 'normal', 'level' => ['in', '2,3']])->column('range_pf'));
                }
                $reseller_user = $reseller_user_arr[$k];
                // dump($drama_reseller);
                if ($drama_reseller['level'] == 1) {
                    $drama_reseller['range'] = $drama_reseller['direct'];
                    // $drama_reseller['range'] = $drama_reseller['range'] == 0 ? $drama_reseller['direct'] : $drama_reseller['range'];
                }
                if ($drama_reseller['range'] > 0) {
                    $ratio = $drama_reseller['range'];
                    if ($order_type == 'usable') {
                        if(in_array(1,$key_arr) && in_array(3,$key_arr) && !in_array(2,$key_arr)){
                            $ratio=$d_r_sum;
                        }
                    }else{
                        if ($drama_reseller['level'] == 2) {
                            $d_r_sum -= $ratio;
                        }
                        if ($drama_reseller['level'] == 3) {
                            $ratio = $d_r_sum;
                        }
                    }
                    
                    if ($level == 1) {
                        $ratio = $drama_reseller['direct'];
                        $money = bcmul($order['pay_fee'], $ratio / 100, 2);
                        $type = 'direct';
                        $msg = '直接销售奖';
                    } else {

                        // dump($d_r_sum);
                        $money = bcmul($order['pay_fee'], $ratio / 100, 2);
                        $type = 'indirect_t_l';
                        $msg = '极差奖金';
                        $option = 0;
                    }
                    $level++;
                    $params = [
                        'reseller_user_id' => $v,
                        'site_id' => $order['site_id'],
                        'user_id' => $order['user_id'],
                        'pay_money' => $order['pay_fee'],
                        'order_type' => $order_type,
                        'order_id' => $order['id'],
                        'type' => $type,
                        'ratio' => $ratio,
                        'money' => $money,
                        'option' => $option,
                        'msg' => $msg,
                    ];
                    // dump($reseller_user);
                    dump($params);
                    // $this->reseller_log_add($params, $money, $reseller_user, $msg, $option);
                    // if ($params['money'] > 0) {
                    // 查询同级的上级
                    $reseller_user = Db::name('drama_reseller_user')
                        ->where('user_id', $reseller_user['reseller_user_id'])
                        ->where('type', 1)
                        ->find();

                    $user_info = Db::name('user')->find($reseller_user['reseller_user_id']);
                    if ($reseller_user && $user_info) {
                        $reseller_bind = ResellerBind::where('user_id', $reseller_user['reseller_user_id'])->where('level', $k)->find();
                        if ($reseller_bind) {
                            $drama_reseller = Db::name('drama_reseller')->find($reseller_bind['reseller_id']);
                            if ($order_type == 'usable') {
                                $drama_reseller['direct'] = $drama_reseller['direct_pf'];
                                $drama_reseller['range'] = $drama_reseller['range_pf'];
                                $drama_reseller['indirect'] = $drama_reseller['indirect_pf'];
                            }
                            // 如果有同级的上级 平级返佣
                            $money = bcmul($params['money'], $drama_reseller['indirect'] / 100, 2);
                            $params = [
                                'reseller_user_id' => $reseller_bind['user_id'],
                                'site_id' => $order['site_id'],
                                'user_id' => $order['user_id'],
                                'pay_money' => $order['pay_fee'],
                                'order_type' => $order_type,
                                'order_id' => $order['id'],
                                'type' => 'indirect',
                                'ratio' => $drama_reseller['indirect'],
                                'money' => $money,
                                'option' => 0,
                                // 'msg' => '平级管理奖',
                            ];
                            // dump($reseller_user);
                            dump($params);
                            // $this->reseller_log_add($params, $money, $reseller_user, $msg, $option);

                        }
                    }

                    // }
                }

                // $msg = '平级管理奖';
                // $params['type'] = 'indirect';
                // dump($drama_reseller);
            }
            dump($arr);
            die;
        }
    }
    public function reseller_log_add($params_class, $reseller_money_class, $reseller_user_class, $msg_class, $option)
    {
        // dump($params_class);
        $reseller_log = ResellerLog::create($params_class);
        // 查询齐全值够不够
        // dump($params_class['order_type']);
        if ($params_class['order_type'] == 'usable') {
            if ($reseller_money_class > 0) {
                \addons\drama\model\User::money_pf(
                    $reseller_money_class,
                    $reseller_user_class['reseller_user_id'],
                    'commission_income',
                    $reseller_log->id,
                    $msg_class,
                    [
                        'reseller_log_id' => $reseller_log->id,
                        'user_id' => $reseller_log->user_id,
                        'parent_id' => $reseller_user_class['parent_id'],
                        'reseller_user_id' => $reseller_log->reseller_user_id
                    ],
                    $option,
                    $params_class['site_id']
                );
            }
        } else {
            if ($reseller_money_class > 0) {
                \addons\drama\model\User::money(
                    $reseller_money_class,
                    $reseller_user_class['reseller_user_id'],
                    'commission_income',
                    $reseller_log->id,
                    $msg_class,
                    [
                        'reseller_log_id' => $reseller_log->id,
                        'user_id' => $reseller_log->user_id,
                        'parent_id' => $reseller_user_class['parent_id'],
                        'reseller_user_id' => $reseller_log->reseller_user_id
                    ],
                    $option,
                    $params_class['site_id']
                );
            }
        }
    }
    /**
     *
     */
    public function jssdk()
    {
        $params = $this->request->post();
        $apis = [
            'checkJsApi',
            'updateTimelineShareData',
            'updateAppMessageShareData',
            "onMenuShareAppMessage",
            "onMenuShareTimeline",
            'getLocation', //获取位置
            'openLocation', //打开位置
            'scanQRCode', //扫一扫接口
            'chooseWXPay', //微信支付
            'chooseImage', //拍照或从手机相册中选图接口
            'previewImage', //预览图片接口       'uploadImage', //上传图片
            'openAddress',   // 获取微信地址
        ];
        // $openTagList = [
        //     'wx-open-subscribe'
        // ];

        $uri = urldecode($params['uri']);

        try {
            $wechat = new WechatLibrary('wxOfficialAccount');

            $jssdk = $wechat->getApp()->jssdk->setUrl($uri);
            // easywechat 版本 < 4.2.33 的 buildConfig 方法 没有 openTagList 参数，手动覆盖底层 buildConfig 方法
            $res = $wechat->buildConfig($jssdk, $apis, $debug = false, $beta = false, $json = false);
        } catch (HttpException $e) {
            $this->error('公众号配置信息错误:' . $e->getMessage());
        }

        $this->success('sdk', $res);
    }


    //签名验证公共接口
    private function valid()
    {
        $echoStr = $_GET["echostr"];
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $config = Config::getEasyWechatConfig('wxOfficialAccount');
        $token = $config['token'];
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 回复消息
     */
    private function response($replyInfo, $event = 'text')
    {
        switch ($event) {
            case 'subscribe':
                $replyInfo['EventKey'] = str_replace('qrscene_', '', $replyInfo['EventKey']);
                $key = $replyInfo['EventKey'];
                if (Cache::has($key)) {
                    $time = @json_decode(Cache::get($key), true)['time'];
                    $expire = $time - time();
                    if ($expire > 0) {
                        $key_data = [
                            'sao' => 1,
                            'auth' => 0,
                            'register' => 0,
                            'openid' => $this->userOpenId,
                            'data' => [],
                            'time' => $time
                        ];
                        Cache::set($key, json_encode($key_data), $expire);
                    } else {
                        $message = [
                            'type'        => 'text',
                            'content'       => '授权已失效，请刷新后重新扫码',
                        ];
                        break;
                    }
                } else {
                    $message = [
                        'type'        => 'text',
                        'content'       => '授权已失效，请刷新后重新扫码',
                    ];
                    break;
                }
                $sign = request()->param('sign');
                $url = urlencode(request()->domain() . '/addons/drama/user/wxOfficialAccountLogin?key=' . $key . '&sign=' . $sign);
                $config = Config::getEasyWechatConfig('wxOfficialAccount');
                $oauthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$config['app_id']}&redirect_uri={$url}&response_type=code&scope=snsapi_userinfo&state=1";
                $configModel = new \addons\drama\model\Config;
                $system = $configModel->where('site_id', $this->site_id)->where('name', 'drama')->value('value');
                // 基本设置
                $system = json_decode($system, true);
                $logo = (isset($system['logo']) && $system['logo']) ? cdnurl($system['logo'], true) :  cdnurl('/assets/img/logo.png', true);
                $message = [
                    'type'        => 'link',
                    'title'       => '登陆授权',
                    'description' => '请点击授权微信号登陆，如不是自己操作请忽略！',
                    'url'         => $oauthUrl,
                    'image'       => $logo,
                ];
                break;
            case 'SCAN': //解析扫码事件EventKey
                $key = $replyInfo['EventKey'];
                if (Cache::has($key)) {
                    $time = @json_decode(Cache::get($key), true)['time'];
                    $expire = $time - time();
                    if ($expire > 0) {
                        $key_data = [
                            'sao' => 1,
                            'auth' => 0,
                            'register' => 0,
                            'openid' => $this->userOpenId,
                            'data' => [],
                            'time' => $time
                        ];
                        Cache::set($key, json_encode($key_data), $expire);
                    } else {
                        $message = [
                            'type'        => 'text',
                            'content'       => '授权已失效，请刷新后重新扫码',
                        ];
                        return $this->response($message);
                    }
                } else {
                    $message = [
                        'type'        => 'text',
                        'content'       => '授权已失效，请刷新后重新扫码',
                    ];
                    break;
                }
                $sign = request()->param('sign');
                $url = urlencode(request()->domain() . '/addons/drama/user/wxOfficialAccountLogin?key=' . $key . '&sign=' . $sign);
                $config = Config::getEasyWechatConfig('wxOfficialAccount');
                $oauthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$config['app_id']}&redirect_uri={$url}&response_type=code&scope=snsapi_userinfo&state=1";
                $configModel = new \addons\drama\model\Config;
                $system = $configModel->where('site_id', $this->site_id)->where('name', 'drama')->value('value');
                // 基本设置
                $system = json_decode($system, true);
                $logo = (isset($system['logo']) && $system['logo']) ? cdnurl($system['logo'], true) :  cdnurl('/assets/img/logo.png', true);
                $message = [
                    'type'        => 'link',
                    'title'       => '登陆授权',
                    'description' => '请点击授权微信号登陆，如不是自己操作请忽略！',
                    'url'         => $oauthUrl,
                    'image'       => cdnurl($logo, true),
                ];
                break;
            case 'CLICK': //解析菜单点击事件EventKey
                $key = explode('|', $replyInfo['EventKey']);
                if ($key) {
                    $message['type'] = $key[0];
                    if ($key[0] === 'text') {
                        $message['content'] =  json_decode(WechatModel::get($key[1])->content, true);
                    } elseif ($key[0] === 'link') {
                        $link = WechatModel::get($key[1]);
                        $message = array_merge($message, json_decode($link->content, true));
                        $message['title'] = $link->name;
                        // return json_encode($message);
                    } else {
                        $message['media_id'] = $key[1];
                    }
                }
                break;
            default:
                $message = json_decode($replyInfo['content'], true);
                break;
        }

        switch ($message['type']) {
            case 'text':  //回复文本
                $content = new \EasyWeChat\Kernel\Messages\Text($message['content']);
                break;
            case 'image': //回复图片
                $content = new \EasyWeChat\Kernel\Messages\Image($message['media_id']);
                break;
            case 'news': //回复图文
                $message = new \EasyWeChat\Kernel\Messages\Media($message['media_id'], 'mpnews');
                $this->app->customer_service->message($message)->to($this->userOpenId)->send();  //素材消息使用客服接口回复
                break;
            case 'voice': //回复语音
                $content = new \EasyWeChat\Kernel\Messages\Voice($message['media_id']);
                break;
            case 'video': //回复视频
                $content = new \EasyWeChat\Kernel\Messages\Video($message['media_id']);
                break;
            case 'link': //回复链接
                $items = new  \EasyWeChat\Kernel\Messages\NewsItem([
                    'title'       => $message['title'],
                    'description' => $message['description'],
                    'url'         => $message['url'],
                    'image'       => cdnurl($message['image'], true),
                ]);
                $content = new \EasyWeChat\Kernel\Messages\News([$items]);
                break;
        }

        return $content;
    }
}
